import store from "@/store";
import {showMessage} from "./axios";
let websock = null;
let onMessage = "";
let connect = false;

function init(url, cb) {
  if (typeof(WebSocket) === "undefined") {
    showMessage("error", "您的浏览器不支持socket");
    return;
  }
  onMessage = cb;
  websock = new WebSocket(url);
  websock.onopen = websockOpen;
  websock.onclose = websockClose;
  websock.onerror = websockError;
  websock.onmessage = websockMessage;
}

function send(msg) {
  if (websock == null || !connect) {
    setTimeout(() => send(msg), 500)
  }else{
    websock.send(JSON.stringify(msg));
  }
}

function close(){
  if(websock){
    websock.close();
  }
}

function websockOpen() {
   connect = true;
}

function websockClose() {
  connect = false;
  store.commit("logout");
}

function websockError() {
  showMessage("error", "后台通讯失败,请联系相关人员处理");
}

function websockMessage(e) {
  const data = JSON.parse(e.data);
  store.commit(onMessage, data);
}

export default {
  init,
  send,
  close
}
